using System;
using System.Linq;
using Microsoft.Web.Administration;

namespace DeVierKoeden.Dynamicweb.CreateSite.Extensions
{
  internal static class IisManagerExtensions
  {
    private static readonly string StandardAppFolder = Configuration.GetAppSetting("StandardAppFolder");
    internal static bool IsCustomSolution(this Site site)
    {
      return site.Applications[0].VirtualDirectories.Any(x => x.Path.Equals("/admin", StringComparison.CurrentCultureIgnoreCase));
    }

    internal static bool IsDynamicwebSite(this Site site)
    {
      return site.Applications[0].VirtualDirectories.Any(x =>
        (x.Path.Equals("/admin", StringComparison.CurrentCultureIgnoreCase) &&
         x.PhysicalPath.StartsWith(StandardAppFolder, StringComparison.CurrentCultureIgnoreCase))
        ||
        (x.Path.Equals("/", StringComparison.CurrentCultureIgnoreCase) &&
         x.PhysicalPath.StartsWith(StandardAppFolder, StringComparison.CurrentCultureIgnoreCase))
        );
    }

    internal static string GetFilesPath(this Site site)
    {
      return site.Applications[0].VirtualDirectories.First(x => x.Path.Equals("/files", StringComparison.CurrentCultureIgnoreCase)).PhysicalPath;
    }

    internal static string GetRootPath(this Site site)
    {
      return site.Applications[0].VirtualDirectories.First(x => x.Path.Equals("/", StringComparison.CurrentCultureIgnoreCase)).PhysicalPath;
    }

    internal static string GetSqlServerInstance(this Site site)
    {
      return SiteInfoProvider.GetSettingFromDynamicwebGlobalSettings(site.GetFilesPath(), "/Globalsettings/System/Database/SQLServer");
    }
    internal static bool UsesIntegratedSecurity(this Site site)
    {
      return Convert.ToBoolean(SiteInfoProvider.GetSettingFromDynamicwebGlobalSettings(site.GetFilesPath(), "/Globalsettings/System/Database/IntegratedSecurity"));
    }

    internal static string GetDatabaseName(this Site site)
    {
      return SiteInfoProvider.GetSettingFromDynamicwebGlobalSettings(site.GetFilesPath(), "/Globalsettings/System/Database/Database");
    }

    internal static string GetApplicationPoolName(this Site site)
    {
      return site.Applications[0].ApplicationPoolName;
    }

    internal static string GetAdminPath(this Site site)
    {
      var path = site.Applications[0].VirtualDirectories.FirstOrDefault(x => x.Path.Equals("/admin", StringComparison.CurrentCultureIgnoreCase));
      if (path == null)
      {
        return "";
      }
      return path.PhysicalPath;
    }
  }
}
